package top.as.sean.api.config;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjUtil;
import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import top.as.sean.common.exception.GlobalException;
import top.as.sean.common.response.RespStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 用户拦截器，解析jwt，锁续期，封装当前用户信息
 *
 * @author: ArchieSean
 * @create: 2022/11/5
 */
@Slf4j
@RequiredArgsConstructor
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) {
        //获取token
        String token = request.getHeader("token");
        //获取请求uri
        String uri = request.getRequestURI();
        if (StringUtils.hasLength(token)) {

            //校验token是否过期
            StpUtil.checkActivityTimeout();

            long tokenTimeout = StpUtil.getTokenTimeout();
            //有效期低于15分钟，自动续期30分钟
            long MIDDLE_TIME = 900L;
            if (tokenTimeout <= MIDDLE_TIME) {
                //token续期
                long MAX_TIME = 1800L;
                StpUtil.renewTimeout(MAX_TIME);
            }
            Object username = StpUtil.getExtra("username");
            Object userId = StpUtil.getExtra("userId");
            String usernameStr = ObjUtil.isNotEmpty(username) ? username.toString() : "system";
            long userIdL = ObjUtil.isNotEmpty(userId) ? Long.parseLong(userId.toString()) : 0L;
            Map<String, Object> map = Maps.newHashMap();
            map.put(UserHandler.USER_NAME, usernameStr);
            map.put(UserHandler.USER_ID, userIdL);
            UserHandler.setMap(map);
        }
        return Boolean.TRUE;

    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request,
                                @NotNull HttpServletResponse response,
                                @NotNull Object handler,
                                Exception ex) {
        UserHandler.remove();
    }
}
